package legumes.client.ui.widgets.form.item;

import java.util.List;

import legumes.client.services.callbacks.GetUserStoresCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.shared.domain.Store;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;

public class StoreSelectItem extends SelectItem {
	
	private Store selectedStore;
	private Store [] storeAr;
	
	public StoreSelectItem(){
		super("Stores", "Magasins");
		setValue("Loading...");
		setShowTitle(false);
		setWidth(200);
		setTextAlign(Alignment.LEFT);
		setValidateOnExit(true);
		setValidateOnChange(true);
        setValidators(new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				Store pcFound = findStore(value.toString());
				selectedStore = pcFound;
				return selectedStore != null;
			}
			
		});
	}
	
	public Store findStore(String store_){
		for(Store s : storeAr){
			if(s.getStoreName().equalsIgnoreCase(store_)){
				return s;
			}
		}
		return null;
	}

	public Store getSelectedStore() {
		return selectedStore;
	}
	
	public void initData(String userId_, final String storeIdToSelect_){
		RPCCallSequencer callSequencer = new RPCCallSequencer();
		final GetUserStoresCallback getUserStoresCallback = new GetUserStoresCallback(userId_);
		callSequencer.addCall(getUserStoresCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				onStoreListChanged( getUserStoresCallback.getStoreList(), storeIdToSelect_ );
			}
		});
	
		callSequencer.callSequence();
	}
	
	protected void onStoreListChanged(List<Store> storeList_, String storeIdToSelect_){
		storeAr = storeList_.toArray(new Store[0]);
		if(storeList_.size()>0){
			String [] str = new String[storeList_.size()];
			int i=0;
			int indexStoreToSelect = 0;
			for(Store s : storeAr){
				String storeName = s.getStoreName();
				str[i] = storeName;
				if( storeIdToSelect_!=null && storeIdToSelect_.equalsIgnoreCase(storeName)){
					indexStoreToSelect = i;
				}
				i++;
			}
			setValueMap(str);
			setValue(str[indexStoreToSelect]);
			selectedStore = storeAr[0];
		} else {
			setValue("");
		}
	}
}
